package sk.naive.talker.command;

import sk.naive.talker.*;
import sk.naive.talker.adapter.TagConsts;
import sk.naive.talker.message.*;
import sk.naive.talker.util.Utils;

import java.rmi.RemoteException;
import java.util.*;

/**
 * Help command - provides list of all commands and help messages for them.
 *
 * @author <a href="mailto:richter@bgs.sk">Richard Richter</a>
 * @version $Revision: 1.28 $ $Date: 2005/01/19 22:41:27 $
 */
public class Help extends OptionalParameterCommand {
	protected void execWithoutParameter() throws RemoteException {
		StringBuilder sb = new StringBuilder();
		sb.append(getString("help.head", user.getProperties()));
		for (Iterator i = commandDispatcher.getAvailableCommands(user).iterator(); i.hasNext(); ) {
			sb.append(Utils.tag(TagConsts.ITEM) + i.next());
		}
		sb.append(Utils.tag(TagConsts.COLS));
		sb.append(getString("help.tail", user.getProperties()));
		user.send(sb.toString());
	}

	protected void execWithParameter() throws RemoteException {
		try {
			user.send(commandDispatcher.getHelpMessages().getString(params, user.getProperties()));
		} catch (MissingResourceException e) {
			// TODO - nedalo by sa to robit mimo catch blok bez vynimky? :-)
			String foundCommand = Utils.findFirstInCollection(params, commandDispatcher.getAvailableCommands(user), true);
			try {
				StringBuilder sb = new StringBuilder();
				ctxSet(DefaultMessageFactory.CTXKEY_VAL, foundCommand);
				sb.append(getString("help.command.title", user.getProperties()));
				bufferCommandUsage(foundCommand, sb);
				ctxSet(DefaultMessageFactory.CTXKEY_VAL, commandDispatcher.getHelpMessages().getString("c." + foundCommand, user.getProperties()));
				sb.append(getString("help.command.description", user.getProperties()));
				user.send(sb.toString());
			} catch (MissingResourceException ee) {
				user.getProperties().put(DefaultMessageFactory.CTXKEY_VAL, params);
				sendHelper().sendMessage(user, "help.notFound");
			}
		}
	}
}
